<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{{ exam.exam_name }} - 在线考试</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#165DFF',
            secondary: '#36D399',
            accent: '#FF9F43',
            neutral: '#F8FAFC',
            'neutral-dark': '#334155',
            danger: '#F87171'
          }
        }
      }
    };
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .card-shadow {
        box-shadow: 0 10px 40px rgba(15, 23, 42, 0.08);
      }
      .btn-primary {
        @apply bg-primary text-white px-4 py-2 rounded-lg transition-all duration-300 hover:bg-primary/90 active:bg-primary/80;
      }
      .btn-secondary {
        @apply bg-white border border-gray-200 text-neutral-dark px-4 py-2 rounded-lg transition-all duration-300 hover:bg-gray-50 active:bg-gray-100;
      }
      .option-card {
        @apply border border-gray-200 rounded-lg p-4 transition-all duration-200 hover:border-primary hover:bg-primary/5;
      }
      .option-selected {
        @apply border-primary bg-primary/10;
      }
    }
  </style>
</head>
<body class="bg-neutral min-h-screen font-sans text-neutral-dark">
  <div class="min-h-screen flex flex-col">
    <header class="bg-white border-b border-gray-200">
      <div class="container mx-auto px-4 py-4 flex flex-col md:flex-row md:items-center md:justify-between gap-3">
        <div>
          <h1 class="text-2xl font-bold text-primary">{{ exam.exam_name }}</h1>
          <p class="text-sm text-gray-500">科目：{{ exam.exam_subject }} · 时长：{{ exam.duration_minutes }} 分钟</p>
        </div>
        <div class="flex items-center gap-4">
          <div class="flex items-center gap-2">
            <i class="fa fa-user-circle text-primary text-xl"></i>
            <span class="text-sm">{{ student.name }}</span>
          </div>
          {% if remaining_seconds is not none %}
          <div class="px-4 py-2 bg-secondary/10 border border-secondary/30 text-secondary rounded-lg font-medium" id="countdown">
            剩余时间：<span id="countdown-text"></span>
          </div>
          {% endif %}
        </div>
      </div>
    </header>

    <main class="flex-1 container mx-auto px-4 py-6">
      <div class="grid lg:grid-cols-4 gap-6">
        <section class="lg:col-span-3 space-y-6" id="question-area">
          {% for question in questions %}
  {#
    注意：这里将 data-detail-id="{{ question.detail_id }}" 修改为更通用的 data-id="{{ question.question_id }}"
    因为后端传递的是 question_id，而 detail_id 可能不存在，这可以避免模板报错。
  #}
  <article class="bg-white rounded-2xl card-shadow p-6" data-question-id="{{ question.question_id }}" data-id="{{ question.question_id }}" data-render-type="{{ question.render_type }}">
    <header class="flex items-start gap-4 mb-4">
      <div class="w-10 h-10 rounded-full bg-primary/10 text-primary flex items-center justify-center font-semibold">{{ loop.index }}</div>
      <div class="flex-1">
        <div class="flex flex-wrap items-center gap-2 mb-2">
          <span class="inline-flex items-center px-2 py-0.5 text-xs bg-primary/10 text-primary rounded-full">{{ question.type }}</span>
          <span class="inline-flex items-center px-2 py-0.5 text-xs bg-gray-100 text-gray-600 rounded-full">分值：{{ question.score }}</span>
        </div>
        <p class="text-base leading-relaxed">{{ question.question }}</p>
      </div>
    </header>

    {# --- 关键修改区域：选项渲染 --- #}
    {% if question.render_type in ['single', 'multiple'] %}
    <div class="space-y-3">
      {% for option in question.options %}
      <label class="option-card block cursor-pointer" data-option-value="{{ option.value }}">
        <div class="flex items-start gap-3">
          {% if question.render_type == 'single' %}
          <input type="radio" name="question-{{ question.question_id }}" value="{{ option.value }}" class="mt-1.5 w-4 h-4 text-primary focus:ring-primary">
          {% else %}
          <input type="checkbox" name="question-{{ question.question_id }}" value="{{ option.value }}" class="mt-1.5 w-4 h-4 text-primary focus:ring-primary">
          {% endif %}
          {#
            修改点 1: 将外层 div 的 class 改为 "flex-1"，让内容区域自适应宽度。
            修改点 2: 【关键修复】在 p 标签中同时显示 option.label 和 option.content，并用点号连接。
          #}
          <div class="flex-1">
            <p class="font-medium">{{ option.label }}. {{ option.content }}</p>
          </div>
        </div>
      </label>
      {% endfor %}
    </div>
    {% elif question.render_type == 'text' %}
    <div>
      <input type="text" name="question-{{ question.question_id }}" class="w-full border border-gray-200 rounded-lg px-4 py-2 focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary" placeholder="请输入答案">
    </div>
    {% else %}
    <div>
      <textarea name="question-{{ question.question_id }}" rows="4" class="w-full border border-gray-200 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary" placeholder="请在此作答"></textarea>
    </div>
    {% endif %}
  </article>
{% endfor %}

        </section>

        <aside class="lg:col-span-1">
          <div class="bg-white rounded-2xl card-shadow p-6 sticky top-6">
            <h2 class="text-lg font-semibold mb-4">作答情况</h2>
            <div class="grid grid-cols-5 gap-2 mb-6" id="answer-status">
              {% for question in questions %}
              <button type="button" class="w-10 h-10 rounded-lg border border-gray-200 text-sm font-medium hover:border-primary focus:outline-none" data-index="{{ loop.index0 }}">{{ loop.index }}</button>
              {% endfor %}
            </div>
            <div class="space-y-3">
              <button id="submit-btn" class="btn-primary w-full flex items-center justify-center gap-2">
                <i class="fa fa-paper-plane"></i>
                提交试卷
              </button>
              <button id="save-btn" class="btn-secondary w-full flex items-center justify-center gap-2">
                <i class="fa fa-save"></i>
                暂存答案
              </button>
            </div>
          </div>
        </aside>
      </div>
    </main>
  </div>

  <script>
    const countdownText = document.getElementById('countdown-text');
    const remainingSeconds = {{ remaining_seconds if remaining_seconds is not none else 'null' }};

    function formatDuration(seconds) {
      if (seconds <= 0) return '时间已到';
      const hrs = Math.floor(seconds / 3600);
      const mins = Math.floor((seconds % 3600) / 60);
      const secs = seconds % 60;
      const parts = [];
      if (hrs) parts.push(`${hrs}小时`);
      if (mins) parts.push(`${mins}分钟`);
      parts.push(`${secs}秒`);
      return parts.join(' ');
    }

    if (remainingSeconds !== null && countdownText) {
      let timeLeft = remainingSeconds;
      countdownText.textContent = formatDuration(timeLeft);
      const timer = setInterval(() => {
        timeLeft -= 1;
        if (timeLeft <= 0) {
          clearInterval(timer);
          countdownText.textContent = '时间已到';
          submitExam(true);
        } else {
          countdownText.textContent = formatDuration(timeLeft);
        }
      }, 1000);
    }

    const questionCards = document.querySelectorAll('[data-question-id]');
    const answerStatusButtons = document.querySelectorAll('#answer-status button');

    function updateAnswerStatus() {
      questionCards.forEach((card, index) => {
        const inputs = card.querySelectorAll('input, textarea');
        const answered = Array.from(inputs).some(input => {
          if (input.type === 'radio' || input.type === 'checkbox') {
            return input.checked;
          }
          return input.value.trim() !== '';
        });
        answerStatusButtons[index].classList.toggle('bg-primary', answered);
        answerStatusButtons[index].classList.toggle('text-white', answered);
        answerStatusButtons[index].classList.toggle('border-primary', answered);
      });
    }

    questionCards.forEach(card => {
      card.addEventListener('change', updateAnswerStatus);
      card.addEventListener('input', updateAnswerStatus);
    });

    answerStatusButtons.forEach((btn, index) => {
      btn.addEventListener('click', () => {
        questionCards[index].scrollIntoView({ behavior: 'smooth', block: 'center' });
        questionCards[index].classList.add('ring-2', 'ring-primary/60');
        setTimeout(() => {
          questionCards[index].classList.remove('ring-2', 'ring-primary/60');
        }, 1500);
      });
    });

    function collectAnswers() {
      const answers = [];
      questionCards.forEach(card => {
        const questionId = card.dataset.questionId;
        const detailId = card.dataset.detailId;
        const renderType = card.dataset.renderType;
        const inputs = card.querySelectorAll('input, textarea');
        let answerValue = null;

        if (renderType === 'single') {
          const checked = Array.from(inputs).find(input => input.type === 'radio' && input.checked);
          answerValue = checked ? checked.value : null;
        } else if (renderType === 'multiple') {
          const checkedValues = Array.from(inputs)
            .filter(input => input.type === 'checkbox' && input.checked)
            .map(input => input.value);
          answerValue = checkedValues;
        } else if (renderType === 'text') {
          answerValue = inputs[0].value.trim();
        } else {
          answerValue = inputs[0].value.trim();
        }

        answers.push({ question_id: Number(questionId), detail_id: Number(detailId), answer: answerValue });
      });
      return answers;
    }

    async function submitExam(auto = false) {
      const payload = { answers: collectAnswers(), auto_submit: auto };
      const response = await fetch('{{ url_for('submit_exam', exam_id=exam.id) }}', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload)
      });
      const result = await response.json();
      if (result.success) {
        alert(auto ? '考试时间到，系统已自动提交。' : '提交成功！');
        // 使用服务器返回的重定向URL，如果没有则使用默认的Waiting_exam
        window.location.href = result.redirect || '{{ url_for('Waiting_exam') }}';
      } else {
        alert(result.message || '提交失败，请稍后再试。');
      }
    }

    document.getElementById('submit-btn').addEventListener('click', () => {
      if (confirm('确认提交试卷吗？提交后将无法修改。')) {
        submitExam(false);
      }
    });

    document.getElementById('save-btn').addEventListener('click', async () => {
      const payload = { answers: collectAnswers() };
      try {
        const response = await fetch('{{ url_for('save_exam_answer', exam_id=exam.id) }}', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(payload)
        });
        const result = await response.json();
        if (result.success) {
          // 同时保存到本地存储作为备份
          localStorage.setItem('exam_draft_{{ exam.id }}', JSON.stringify(payload));
          alert('答案已保存到服务器！');
        } else {
          alert(result.message || '保存失败，请稍后再试。');
        }
      } catch (error) {
        console.error('保存答案时出错:', error);
        // 如果服务器保存失败，至少保存到本地
        localStorage.setItem('exam_draft_{{ exam.id }}', JSON.stringify(payload));
        alert('服务器保存失败，已保存到浏览器本地。');
      }
    });

    const draft = localStorage.getItem('exam_draft_{{ exam.id }}');
    if (draft) {
      try {
        const parsed = JSON.parse(draft);
        (parsed.answers || []).forEach(item => {
          const card = document.querySelector(`[data-question-id="${item.question_id}"]`);
          if (!card) return;
          const renderType = card.dataset.renderType;
          if (renderType === 'single') {
            const target = card.querySelector(`input[type="radio"][value="${item.answer}"]`);
            if (target) target.checked = true;
          } else if (renderType === 'multiple') {
            (item.answer || []).forEach(val => {
              const checkbox = card.querySelector(`input[type="checkbox"][value="${val}"]`);
              if (checkbox) checkbox.checked = true;
            });
          } else {
            const input = card.querySelector('input, textarea');
            if (input && item.answer) input.value = item.answer;
          }
        });
        updateAnswerStatus();
      } catch (error) {
        console.warn('无法解析草稿答案', error);
      }
    }
  </script>
</body>
</html>
